package com.csrcb.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Classname CalcTime
 * @Description 计算发送次数的，若达到5次停止发送
 * @Date 2020/12/17 18:35
 * @Created by gangye
 */
public class CalcTime {
    private static Logger logger = LoggerFactory.getLogger(CalcTime.class);

    public static final Properties prop = new Properties();
    public static final String path = "calcTimes.properties";

    /**
     * 通过类加载器 初始化Properties
     */
    public static void init(){
        //转换成流
        InputStream is =CalcTime.class.getClassLoader().getResourceAsStream(path);
        try {
            //从流中读取属性列表(键和元素对
            prop.load(is);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 通过key获取value
     * @param key
     * @return
     */
    public static String get(String key) {
        return prop.getProperty(key);
    }

    /**
     * 修改或者新增key
     * @param key
     * @param value
     */
    public static void update(String key, String value) {
        prop.setProperty(key, value);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path);
            //将Properties中的属性列表（键和元素对）写入输出流
            prop.store(oFile, "");
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 通过key删除value
     * @param key
     */
    public static void delete(String key) {
        prop.remove(key);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path);
            prop.store(oFile, "");
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 循环所有key value
     */
    public static Map<String,String> list() {
        Enumeration en = prop.propertyNames(); //得到配置文件的名字
        Map<String,String> valMap = new HashMap<>();
        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = prop.getProperty(strKey);
            valMap.put(strKey,strValue);
        }
        return valMap;
    }
}
